package com.hyk.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyk.domain.User;
import com.hyk.domain.UserWallet;
import com.hyk.dto.CoinDto;
import com.hyk.feign.CoinFeign;
import com.hyk.mapper.UserWalletMapper;
import com.hyk.service.UserService;
import com.hyk.service.UserWalletService;
import com.hyk.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Map;

@Service
public class UserWalletServiceImpl extends ServiceImpl<UserWalletMapper, UserWallet> implements UserWalletService{

    @Autowired
    private UserService userService;

    @Resource
    private CoinFeign coinFeign;

    @Override
    public void saveUserWallet(UserWallet userWallet) {
        //校验交易支付密码
        User user = userService.getById(UserUtils.getUser());

        if(StringUtils.isBlank(user.getPaypassword())){
            throw new IllegalArgumentException("请先去设置支付密码");
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if(!bCryptPasswordEncoder.matches(userWallet.getPayPassword(),user.getPaypassword())){
            throw new IllegalArgumentException("支付密码错误");
        }

        Map<Long, CoinDto> coinByIds = coinFeign.getCoinByIds(Arrays.asList(userWallet.getCoinId()));
        if(coinByIds == null){
            throw new IllegalArgumentException("请先配置币种");
        }

        userWallet.setCoinName(coinByIds.get(userWallet.getCoinId()).getName());
        userWallet.setSort(1);
        userWallet.setUserId(UserUtils.getUser());
        userWallet.setStatus((byte)1);

        save(userWallet);
    }
}
